import { cardApi } from '../lib/cardApi';
import { TrendCardData } from '../types/trendCard';
import { formatPercentage } from '../utils/numberFormat';

// 定义数据线颜色列表（除去红色和绿色）
const DATA_LINE_COLORS = [
  '#3B82F6', // 蓝色
  '#8B5CF6', // 紫色
  '#F59E0B', // 橙色
  '#06B6D4', // 青色
  '#EC4899', // 粉色
  '#6366F1', // 靛蓝色
  '#10B981', // 翠绿色（虽然包含绿色，但主要用于区分）
  '#F97316', // 深橙色
  '#8B5A2B', // 棕色
  '#6B7280', // 灰色
  '#1E40AF', // 深蓝色
  '#7C3AED', // 深紫色
];

export const transformApiDataToTrendCard = (apiData: any, cardContent: string): TrendCardData => {
  // 兼容 data 不是数组的情况
  const dataArray = Array.isArray(apiData.data) ? apiData.data : [];
  
  // 计算收益率
  const calculateReturn = (data: any[]): { return: string; isPositive: boolean } => {
    if (data.length < 2) return { return: '+0.00%', isPositive: false };
    const firstValue = data[0][1];
    const lastValue = data[data.length - 1][1];
    const returnValue = lastValue - firstValue;
    const isPositive = returnValue >= 0;
    return {
      return: formatPercentage(returnValue, 2, true),
      isPositive
    };
  };

  // 转换数据格式：从[dateStr, value]转换为{date: string, value: number}
  const convertDataFormat = (data: any[]): { date: string; value: number }[] => {
    return data.map(([dateStr, value]) => ({
      date: dateStr,
      value: value
    }));
  };

  // 计算日期范围
  const getDateRange = (data: any[]): { start: string; end: string } => {
    if (data.length === 0) {
      const now = new Date();
      const threeMonthsAgo = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
      return {
        start: threeMonthsAgo.toISOString().split('T')[0],
        end: now.toISOString().split('T')[0]
      };
    }
    return {
      start: data[0][0],
      end: data[data.length - 1][0]
    };
  };

  // 动态生成数据线
  const generateDataLines = (dataArray: any[]): TrendCardData['dataLines'] => {
    return dataArray.map((item, index) => {
      const color = DATA_LINE_COLORS[index % DATA_LINE_COLORS.length];
      const data = item.data || [];
      
      return {
        name: item.name,
        color,
        ...calculateReturn(data),
        data: convertDataFormat(data)
      };
    });
  };

  const dataLines = generateDataLines(dataArray);
  const dateRange = dataLines.length > 0 ? getDateRange(dataLines[0].data) : getDateRange([]);
  const timeRange = apiData.time_range || '近一月';

  return {
    id: `trend_card_${cardContent}_${Date.now()}`,
    title: apiData.fund_name || cardContent,
    subtitle: apiData.indicator || '趋势图',
    timeRange: timeRange,
    dataLines,
    timePeriods: [
      { label: '近一周', value: '1w', active: false },
      { label: '近一月', value: '1m', active: timeRange === '近一月' },
      { label: '近三月', value: '3m', active: timeRange === '近三月' },
      { label: '近六月', value: '6m', active: false },
      { label: '近一年', value: '1y', active: timeRange === '近一年' }
    ],
    dateRange
  };
};

export const trendCardService = {
  getTrendCardByCardContent: async (cardContent: string): Promise<TrendCardData | null> => {
    try {
      let response = await cardApi.getCardByCardContent(cardContent);
      if (!response.success) {
        console.error('获取卡片数据失败:', response.error);
        return null;
      }
      const trendCardData = transformApiDataToTrendCard(response.data, cardContent);
      return trendCardData;
    } catch (error) {
      console.error('获取卡片数据时发生错误:', error);
      return null;
    }
  }
};